const Path = require('path');
const less = require('less');
const CommonJsLoader = require('./CommonJsLoader');

function buildCss(code) {
    return `\n\nvar style=document.createElement("style");
    style.innerHTML="${code
        .replace(/\\/g, '\\\\')
        .replace(/"/g, '\\"')
        .replace(/\r/g, '\\r')
        .replace(/\n/g, '\\n')
        .replace(/\t/g, '\\t')
    }";
    document.body.appendChild(style);`;
}
module.exports = async function LessLoader(module, opt) {
    let code = await less.render(module.file.contents.toString(opt.encoding || 'UTF-8'), {
        paths: [Path.dirname(module.file.path)],
        filename: Path.basename(module.file.path),
        modifyVars: opt.lessVars
    });
    if (code.css) {
        module.code = buildCss(code.css);
    }
    return CommonJsLoader(module, opt);
};
